package com.zahb.qadx.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.zahb.qadx.R;

/**
 * Created by Zdw on 2021/04/29 15:33
 */
public class BorderTextView extends AppCompatTextView {

    private Paint mPaint;
    private int mBorderColor = Color.parseColor("#D9D9D9");
    private float mBorderWidth = 1f;
    private boolean mFill;
    private int mCornerRadius;

    public BorderTextView(Context context) {
        this(context, null);
    }

    public BorderTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BorderTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.BorderTextView, defStyleAttr, 0);
        mBorderWidth = array.getDimension(R.styleable.BorderTextView_z_border_width, mBorderWidth);
        mBorderColor = array.getColor(R.styleable.BorderTextView_z_border_color, mBorderColor);
        mCornerRadius = array.getDimensionPixelSize(R.styleable.BorderTextView_z_border_corners, mCornerRadius);
        mFill = array.getBoolean(R.styleable.BorderTextView_z_border_fill, mFill);
        array.recycle();
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    public BorderTextView setBorderColor(int borderColor) {
        if (mBorderColor != borderColor) {
            mBorderColor = borderColor;
            postInvalidate();
        }
        return this;
    }

    public BorderTextView setBorderWidth(float borderWidth) {
        if (mBorderWidth != borderWidth) {
            mBorderWidth = borderWidth;
            postInvalidate();
        }
        return this;
    }

    public BorderTextView setFill(boolean fill) {
        if (mFill != fill) {
            mFill = fill;
            postInvalidate();
        }
        return this;
    }

    public BorderTextView setCornerRadius(int cornerRadius) {
        if (mCornerRadius != cornerRadius) {
            mCornerRadius = cornerRadius;
            postInvalidate();
        }
        return this;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(mBorderColor);
        mPaint.setStrokeWidth(mBorderWidth);
        mPaint.setStyle(mFill ? Paint.Style.FILL_AND_STROKE : Paint.Style.STROKE);
        canvas.drawRoundRect(0 + mBorderWidth / 2, 0 + mBorderWidth / 2,
                getWidth() - mBorderWidth / 2, getHeight() - mBorderWidth / 2,
                mCornerRadius, mCornerRadius, mPaint);
        super.onDraw(canvas);
    }
}
